package com.yunhe.authority.controller.authority;

import com.yunhe.authority.domain.app.AppPushInfo;
import com.yunhe.authority.domain.authority.Firm;
import com.yunhe.authority.domain.authority.ProjectData;
import com.yunhe.authority.domain.authority.Station;
import com.yunhe.authority.domain.authority.User;
import com.yunhe.authority.model.authority.AppLogin;
import com.yunhe.authority.option.UserProperties;
import com.yunhe.authority.service.app.AppPushInfoService;
import com.yunhe.authority.service.authority.TokenService;
import com.yunhe.authority.service.authority.UserService;
import com.yunhe.common.exception.ArgumentErrorException;
import com.yunhe.common.exception.UsernamePasswordException;
import com.yunhe.common.model.ResultObject;
import com.yunhe.common.util.CollectionUtil;
import com.yunhe.common.util.DateTimeUtils;
import com.yunhe.common.util.MD5Util;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @ClassName AppLoginController
 * @Description TODO
 * @Author HeTao
 * @Date 2021/9/6 9:01
 * @Version 1.0
 **/
@Api(value = "appLogin",description = "App登录", tags = {"Authority_Login(App登录)"})
@RestController
@RequestMapping("/appLogin")
public class AppLoginController {

    @Autowired
    private UserService userService;
    @Autowired
    private TokenService tokenService;

    @Autowired
    private AppPushInfoService appPushInfoService;

    @Autowired
    private UserProperties userProperties;

    private static final String SALT_V = "@yqlh";

    @ApiOperation("根据手机号和密码获得用户（执行登录）")
    @RequestMapping(value="/loginByPhone", method = RequestMethod.POST)
    public ResponseEntity<ResultObject<Map>> login(@RequestBody AppLogin appLogin) throws ArgumentErrorException, UsernamePasswordException {
        if (!appLogin.getPhone().isPresent()) {
            throw new UsernamePasswordException("手机号不能为空");
        } else if (!appLogin.getPassword().isPresent()) {
            throw new UsernamePasswordException("密码不能为空");
        }else if(!appLogin.getSystemId().isPresent()){
            throw new UsernamePasswordException("系统标识不能为空");
        }
        User user = userService.findByPhoneAndPassword(appLogin.getPhone().get(), appLogin.getPassword().get());
        if(!user.isBackUser() && "1".equals(appLogin.getSystemId().orElse(null))){
            throw new ArgumentErrorException("当前用户不是后台用户不能登录后台管理平台!");
        }
        if(user.isBackUser() && "2".equals(appLogin.getSystemId().orElse(null))){
            throw new ArgumentErrorException("当前用户不是智慧园区平台用户不能登录智慧园区平台!");
        }
        String token = tokenService.getAppToken(user,appLogin.getSystemId().get());
        Map<String, Object> result = new HashMap<>();
        result.put("token", token);
        result.put("user", user);
        //记录最后登录时间，最后登录系统品平台
        user.setLastLoginSystem(appLogin.getSystemId().get());
        user.setLastLoginTime(DateTimeUtils.format(DateTimeUtils.PATTERN.DATETIME.value(),new Date()));
        userService.saveLoginRecord(user);
        //判断该用户是否是重置密码后第一次登录
        Boolean firstLoginFlag = userService.resetFirstLogin(user.getId());
        result.put("firstLoginFlag",firstLoginFlag);
        if(MD5Util.encode(userProperties.getRootDefaultPassword(), SALT_V).equals(appLogin.getPassword())){
            result.put("firstLoginFlag",false);
        };
        //设置对应的项目
        List<ProjectData> projectDatas = findStationByLoginUser(user);
        if(!CollectionUtil.isEmpty(projectDatas)){
            result.put("project",projectDatas);
            projectDatas.stream().forEach(projectData -> {
                if(projectData.getId().equals(user.getLastAccessProject())){
                    user.setLastAccessProjectTitle(projectData.getTitle());
                }
            });
        }

        //需要去保存app的一些对应消息
        if (appLogin.getRegistrationId().isPresent()
                && appLogin.getDeviceId().isPresent()
                && appLogin.getSystemOs().isPresent()) {
            appPushInfoService.recordUserAppInfo(user.getId(),
                    appLogin.getRegistrationId().get(),
                    appLogin.getDeviceId().get(),
                    appLogin.getSystemOs().get());
        }

        return new ResponseEntity<>(new ResultObject<>(result), HttpStatus.OK);
    }

    private List<ProjectData> findStationByLoginUser(User user) {
        List<ProjectData> result = new ArrayList<>();
        //判断当前登录的账号是单位账号还是园区账号
        List<Firm> firms = user.getFirms();
        List<Station> stations = user.getStations();
        if (!CollectionUtil.isEmpty(stations)) {
            for (Station station : stations) {
                ProjectData projectData = new ProjectData();
                projectData.setId(station.getId());
                projectData.setTitle(station.getEnterpriseFullName());
                projectData.setType("station");
                projectData.setSn(station.getSn());
                result.add(projectData);
            }
        }
        if (!CollectionUtil.isEmpty(firms)) {
            for (Firm firm : firms) {
                ProjectData projectData = new ProjectData();
                projectData.setId(firm.getId());
                projectData.setTitle(firm.getEnterpriseFullName());
                projectData.setType("firm");
                projectData.setSn(firm.getSn());
                result.add(projectData);
            }
        }
        //对集合针对每个ProjectData的sn首字母进行升序排序
        result.sort(Comparator.comparing(ProjectData::getSn));
//        Comparator comparator = Collator.getInstance(Locale.CHINA);
//        if (!CollectionUtil.isEmpty(result)) {
//            result = (List<ProjectData>) result.stream().sorted(comparator.thenComparing(Comparator.comparing(ProjectData::getSn))).collect(Collectors.toList());
//        }
        return result;
    }

    /**
     * 根据手机号和验证码获得用户（执行登录）
     */
    @ApiOperation("根据手机号和验证码获得用户（执行登录）")
    @RequestMapping(value="/loginByVerificationCode", method = RequestMethod.POST)
    public ResponseEntity<ResultObject<Map>> loginByVerificationCode(@RequestBody AppLogin appLogin)
            throws ArgumentErrorException, UsernamePasswordException {
        if (!appLogin.getPhone().isPresent()) {
            throw new UsernamePasswordException("手机号不能为空");
        } else if (!appLogin.getVerificationCode().isPresent()) {
            throw new UsernamePasswordException("验证码不能为空");
        }else if(!appLogin.getSystemId().isPresent()){
            throw new UsernamePasswordException("系统标识不能为空");
        }
        User user = userService.findByPhoneAndVerificationCodeforMob(appLogin.getPhone().get(), appLogin.getVerificationCode().get());
        if(!user.isBackUser() && "1".equals(appLogin.getSystemId().orElse(null))){
            throw new ArgumentErrorException("当前用户不是后台用户不能登录后台管理平台!");
        }
        if(user.isBackUser() && "2".equals(appLogin.getSystemId().orElse(null))){
            throw new ArgumentErrorException("当前用户不是智慧园区平台用户不能登录智慧园区平台!");
        }
        String token = tokenService.getAppToken(user,appLogin.getSystemId().get());
        Map<String, Object> result = new HashMap<>();
        result.put("token", token);
        result.put("user", user);
        //记录最后登录时间，最后登录系统品平台
        user.setLastLoginSystem(appLogin.getSystemId().get());
        user.setLastLoginTime(DateTimeUtils.format(DateTimeUtils.PATTERN.DATETIME.value(),new Date()));
        userService.saveLoginRecord(user);
        //设置对应的项目
        List<ProjectData> projectDatas = findStationByLoginUser(user);
        if(!CollectionUtil.isEmpty(projectDatas)){
            result.put("project",projectDatas);
        }
        //需要去保存app的一些对应消息
        if (appLogin.getRegistrationId().isPresent()
                && appLogin.getDeviceId().isPresent()
                && appLogin.getSystemOs().isPresent()) {
            appPushInfoService.recordUserAppInfo(user.getId(),
                    appLogin.getRegistrationId().get(),
                    appLogin.getDeviceId().get(),
                    appLogin.getSystemOs().get());
        }
        return new ResponseEntity<>(new ResultObject<>(result), HttpStatus.OK);
    }

    @ApiOperation("校验验证码是否正确")
    @RequestMapping(value="/checkVerificationCode", method = RequestMethod.POST)
    public ResponseEntity<ResultObject<Map>> checkVerificationCode(@RequestBody AppLogin appLogin)
            throws ArgumentErrorException, UsernamePasswordException {
        if (!appLogin.getPhone().isPresent()) {
            throw new UsernamePasswordException("手机号不能为空");
        } else if (!appLogin.getVerificationCode().isPresent()) {
            throw new UsernamePasswordException("验证码不能为空");
        }
        return new ResponseEntity(new ResultObject<>(userService.checkVerificationCode(appLogin.getPhone().get(), appLogin.getVerificationCode().get())), HttpStatus.OK);
    }

    @ApiOperation("登出")
    @RequestMapping(value="/logout", method = RequestMethod.POST)
    public ResponseEntity<ResultObject<String>> logout(@RequestBody AppLogin appLogin)
            throws ArgumentErrorException {
        if (!appLogin.getRegistrationId().isPresent()) {
            throw new ArgumentErrorException("推送码不能为空");
        }
        if (!appLogin.getDeviceId().isPresent()) {
            throw new ArgumentErrorException("设备ID不能为空");
        }
        if (!appLogin.getUserId().isPresent()) {
            throw new ArgumentErrorException("用户ID不能为空");
        }
        appPushInfoService.deleteUserAppInfo(appLogin.getUserId().get(),
                appLogin.getRegistrationId().get(),
                appLogin.getDeviceId().get());
        return new ResponseEntity(new ResultObject<>("success"), HttpStatus.OK);
    }
}
